/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 * \file
 * \brief Implementation for TaskCtrl interface client library.
 * \author Antti Maula <antti.maula@tkk.fi>
 *
 * $Id: TaskCtrlClient.cpp,v 1.15 2010-01-05 07:04:12 mmatusia Exp $
 *
 */

#include "TaskCtrlClient.hpp"
#include "TaskCtrlData.hpp"
#include <list>

//*****************************************************************************
using namespace MaCI::TaskCtrl;
//*****************************************************************************
//*****************************************************************************
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

CTaskCtrlClient::CTaskCtrlClient(gimi::GIMI *aGIMIPtr, 
                           const int aInterfaceMinor)
  : CSync(1,1), // Max One Mutex, Max one Condition
    CThread(1), // Max one Thread.
    CMaCI(aGIMIPtr, GIMI_PROTOCOL_MACI_TASKCTRL, aInterfaceMinor, true),
    iCallBackUserPtr(NULL),
    iTaskCtrlDataSequence(0),
    iTaskCtrlCommandSequence(0),
    iLastTaskCtrlData(),
    iTaskCtrlClientCallback(NULL)

    
{
  dPrint(4,"CTaskCtrlClient %p constructed", this);
  EnableSynchronousMessageReply(true);
}
//*****************************************************************************

CTaskCtrlClient::~CTaskCtrlClient()
{
  /*if (iTaskCtrlClientCallback!=NULL) {
      delete iTaskCtrlClientCallback;
  }*/
  /*if (iCallBackUserPtr!=NULL) {
      delete iCallBackUserPtr;
  }*/ 
  DoClose();
  dPrint(1,"CTaskCtrlClient %p destructed", this);
}
//*****************************************************************************

MaCI::EMaCIError CTaskCtrlClient::DoOpen(void)
{

  EMaCIError result = KMaCIError;
  
  // Checks.
  if(!IsActive()) {

    // Do Subs. using the MaCI provided function.
    result = SubscribeToInterface();

    // If all inits were fine...
    if (result == KMaCIOK) {
      // Start the Thread
      SetActive(true);
      CThread::RunThread();
      dPrint(4,"CTaskCtrlClient::DoOpen() was succesfull.");
    }

  } else {
    dPrint(4,"TaskCtrlClient already Active, not Opening again.");
    result = KMaCINotActive;

  }
  
  return result;
}
//*****************************************************************************

MaCI::EMaCIError CTaskCtrlClient::DoClose(void)
{
  EMaCIError result = KMaCIError;
  
  if(IsActive()) {
    SetActive(false);

    // Wait for thread to complete.
    CThread::SetRequestTermination();
    /* CThread::CancelThread(); //Removed by script */
    CThread::WaitThread();

    // Close Sync queue.
    DisableSynchronousMessageReply();

    result = UnsubscribeToInterface(TimeoutValue(2000));
  
    if(result == KMaCIOK){
      dPrint(4,"Succesfully closed TaskCtrlClient");    
    }else{
      dPrint(4,"Unsubscribing failed!");
    }

    
  } else {
    dPrint(4, "TaskCtrlClient not active, so not Closing.");
    result = KMaCINotActive;

  }
  
  return result;
}
//*****************************************************************************

bool CTaskCtrlClient::AddTask( MaCI::TaskCtrl::TTaskCtrlTaskID &aTaskID, 
                              const std::string aTaskSpecificXML,
                              unsigned int aTimeout_ms)
{

  bool result = false;
  CTaskCtrlData dd;
  dd.CreateInternalBinBag();
  CTaskCtrlData dataOut;
  dataOut.CreateInternalBinBag();

  //Add own id
  aTaskID.owner = GetGIMIPtr()->getOwnId();
  bool r = dd.SetCommand(TCommand(KCommandAddTask,
                                  KCommandFlagDefault,
                                  aTaskID,
                                  0));
  assert(r == true);

  r = dd.AddTaskCtrlXMLString(aTaskSpecificXML);
  dPrint(10,"Adding task. Sending:");
  dd.Print(10);
  // Get Unique MessageID
  const unsigned int messageId = GetUniqueMessageID();
  if(GetDataBySynchronousCall(dd,dataOut,messageId,aTimeout_ms)){
    const TCommand *cmd = dataOut.GetCommand();


      if(cmd &&cmd->flags == KCommandFlagReply){
        
        aTaskID = cmd->taskID;
        result = true;
      }else{
        
        dPrint(3,"No cmd-structure or error when adding task in the response packet");
        result = false;
      }      
    
    
  }else{
    dPrint(3,"Didn't got a response from the server");
  }
  return result;

}
//*****************************************************************************

bool CTaskCtrlClient::RemoveTask(const unsigned int aTaskID)
{
  CTaskCtrlData dd;
  dd.CreateInternalBinBag();
  TTaskCtrlTaskID taskID;
  taskID.taskID = aTaskID;
  bool r = dd.SetCommand(TCommand( KCommandRemoveTask,
                                   KCommandFlagDefault,
                                   taskID,
                                   0));
  assert(r== true);
  unsigned int i= 0;
  return SimpleDataSend(dd,i);

}
//*****************************************************************************

bool CTaskCtrlClient::InitTask(const unsigned int aTaskID)
{
  CTaskCtrlData dd;
  dd.CreateInternalBinBag();
  TTaskCtrlTaskID taskID;
  taskID.taskID = aTaskID;
  bool r = dd.SetCommand(TCommand(KCommandSetTaskState,
                                  KCommandFlagDefault,
                                  taskID,
                                  0));
  assert(r == true);
  r = dd.SetTaskCtrlStateCommand(TTaskCtrlStateCommand(KTaskStateCommandInit));

  assert(r == true);
  unsigned int i= 0;
  return SimpleDataSend(dd,i);

                             
}
//*****************************************************************************

bool CTaskCtrlClient::StartTask(const unsigned int aTaskID)
{
  CTaskCtrlData dd;
  dd.CreateInternalBinBag();
  TTaskCtrlTaskID taskID;
  taskID.taskID = aTaskID;
  bool r = dd.SetCommand(TCommand(KCommandSetTaskState,
                                  KCommandFlagDefault,
                                  taskID,
                                  0));
  assert(r == true);
  r = dd.SetTaskCtrlStateCommand(TTaskCtrlStateCommand(KTaskStateCommandStart));

  assert(r == true);
  unsigned int i= 0;
  return SimpleDataSend(dd,i);

}
//*****************************************************************************

bool CTaskCtrlClient::StopTask(const unsigned int aTaskID)
{
  CTaskCtrlData dd;
  dd.CreateInternalBinBag();
  TTaskCtrlTaskID taskID;
  taskID.taskID = aTaskID;
  bool r = dd.SetCommand(TCommand(KCommandSetTaskState,
                                  KCommandFlagDefault,
                                  taskID,
                                  0));
  assert(r == true);
  r = dd.SetTaskCtrlStateCommand(TTaskCtrlStateCommand(KTaskStateCommandStop));

  assert(r == true);
  unsigned int i= 0;
  return SimpleDataSend(dd,i);
  
}
//*****************************************************************************

bool CTaskCtrlClient::PauseTask(const unsigned int aTaskID)
{
  CTaskCtrlData dd;
  dd.CreateInternalBinBag();
  TTaskCtrlTaskID taskID;
  taskID.taskID = aTaskID;
  bool r = dd.SetCommand(TCommand(KCommandSetTaskState,
                                  KCommandFlagDefault,
                                  taskID,
                                  0));
  assert(r == true);
  r = dd.SetTaskCtrlStateCommand(TTaskCtrlStateCommand(KTaskStateCommandPause));

  assert(r == true);
  unsigned int i= 0;
  return SimpleDataSend(dd,i);
  
}
//*****************************************************************************

bool CTaskCtrlClient::ContinueTask(const unsigned int aTaskID)
{
  CTaskCtrlData dd;
  dd.CreateInternalBinBag();
  TTaskCtrlTaskID taskID;
  taskID.taskID = aTaskID;
  bool r = dd.SetCommand(TCommand(KCommandSetTaskState,
                                  KCommandFlagDefault,
                                  taskID,
                                  0));
  assert(r == true);
  r = dd.SetTaskCtrlStateCommand(TTaskCtrlStateCommand(KTaskStateCommandContinue));

  assert(r == true);
  unsigned int i= 0;
  return SimpleDataSend(dd,i);

}
//*****************************************************************************

bool CTaskCtrlClient::GetTaskState(const unsigned int aTaskID, TTaskCtrlTaskState &aState,const unsigned int aTimeout_ms)
{
  CTaskCtrlData dd;
  dd.CreateInternalBinBag();
  CTaskCtrlData dataOut;
  dataOut.CreateInternalBinBag();
  TTaskCtrlTaskID taskID;
  taskID.taskID = aTaskID;
  bool r = dd.SetCommand(TCommand(KCommandGetTaskState,
                             KCommandFlagDefault,
                             taskID,
                             0));
  assert(r== true);

  // Get Unique MessageID
  const unsigned int messageId = GetUniqueMessageID();
  if(GetDataBySynchronousCall(dd,dataOut,messageId,aTimeout_ms)){
    const TCommand *cmd = dataOut.GetCommand();

    
    if(cmd &&cmd->flags == KCommandFlagReply){
      if( dataOut.GetTaskCtrlTaskState()){
        aState = *(dataOut.GetTaskCtrlTaskState());
        
        return true;
      }else{
        dPrint(1,"No taskctrl task state container in response packet :(");
        return false;

      }
    }else{
      dPrint(1,"Error msg sent when getting task state");
      return false;
    }
  }else{
    dPrint(1,"no responce for get task state");
    return false;
  }
}
//*****************************************************************************
bool CTaskCtrlClient::GetTaskLibrary(TTaskCtrlTaskStateArray &aStateArray,std::vector<std::string> &aTasksXML,unsigned int aTimeout_ms)

{
  CTaskCtrlData dd;
  dd.CreateInternalBinBag();
  CTaskCtrlData dataOut;
  dataOut.CreateInternalBinBag();
  bool r = dd.SetCommand(TCommand(KCommandGetCompetences,
                                  KCommandFlagDefault,
                                  TTaskCtrlTaskID(),
                                  0));
  assert(r== true);

  // Get Unique MessageID
  const unsigned int messageId = GetUniqueMessageID();
  if(GetDataBySynchronousCall(dd,dataOut,messageId,aTimeout_ms)){
    const TCommand *cmd = dataOut.GetCommand();

    
    if(cmd &&cmd->flags == KCommandFlagReply){
      dPrint(1,"Got library");
      TTaskCtrlXMLPtrArray xml = dataOut.GetTaskCtrlXMLPtrArray();
      for(unsigned int i = 0; i< xml.size();i++){
        aTasksXML.push_back(xml[i]->GetText());
      }/*        
                 for(EACH_IN_i(dataOut.GetTaskCtrlXMLPtrArray())){
                 aTasksXML.push_back(i->GetText());
                 }
       */
      TTaskCtrlTaskStatePtrArray state = dataOut.GetTaskCtrlTaskStatePtrArray();
      for(unsigned int i = 0; i< state.size();i++){
        const TTaskCtrlTaskState *s = state[i];
        aStateArray.push_back(*s);
        
      }
      
      
      
      return true;
    }else{
      dPrint(1,"No cmd-structure or error from server");
      return false;
    }
    
  }else{
    dPrint(1,"no responce for get competences");
    return false;
  }
}
//*****************************************************************************

bool CTaskCtrlClient::AddTaskToLibrary(TTaskCtrlTaskID &aTaskID,
                                       std::string aTaskSpecificXML,
                                       unsigned int aTimeout_ms,
                                       std::string &errorString)
{
 bool result = false;
  CTaskCtrlData dd;
  dd.CreateInternalBinBag();
  CTaskCtrlData dataOut;
  dataOut.CreateInternalBinBag();
 
  bool r = dd.SetCommand(TCommand(KCommandAddTaskToLibrary,
                                  KCommandFlagDefault,
                                  aTaskID,
                                  0));
  assert(r == true);

  r = dd.AddTaskCtrlXMLString(aTaskSpecificXML);
  dPrint(10,"Adding task. Sending:");
  dd.Print(10);
  // Get Unique MessageID
  const unsigned int messageId = GetUniqueMessageID();
  if(GetDataBySynchronousCall(dd,dataOut,messageId,aTimeout_ms)){
    const TCommand *cmd = dataOut.GetCommand();



    if(cmd &&cmd->flags == KCommandFlagReply){
      
      aTaskID = cmd->taskID;
      result = true;
    }else{
      
      dPrint(3,"No cmd-structure in the response packet or error from server. Error string '%s'",dataOut.GetTaskCtrlErrorString().c_str());
      errorString = dataOut.GetTaskCtrlErrorString();
      result = false;
      
    }      
    
    
  }else{
    dPrint(3,"Didn't got a response from the server");
  }
  return result;


 

}
//*****************************************************************************

bool CTaskCtrlClient::RemoveTaskFromLibrary(TTaskCtrlTaskID aTaskID)
{

  CTaskCtrlData dd;
  dd.CreateInternalBinBag();
 
  bool r = dd.SetCommand(TCommand(KCommandRemoveTaskFromLibrary,
                                  KCommandFlagDefault,
                                  aTaskID,
                                  0));
  assert(r == true);
  unsigned int i= 0;
  return SimpleDataSend(dd,i);


}
//*****************************************************************************

bool CTaskCtrlClient::GetTaskTable(TTaskCtrlTaskStateArray &aStateArray,std::vector<std::string> &aTasksXML,unsigned int aTimeout_ms)
{
 CTaskCtrlData dd;
  dd.CreateInternalBinBag();
  CTaskCtrlData dataOut;
  dataOut.CreateInternalBinBag();
  bool r = dd.SetCommand(TCommand(KCommandGetTasks,
                                  KCommandFlagDefault,
                                  0,
                                  0));
  assert(r== true);

  // Get Unique MessageID
  const unsigned int messageId = GetUniqueMessageID();      
  if(GetDataBySynchronousCall(dd,dataOut,messageId,aTimeout_ms)){
    const TCommand *cmd = dataOut.GetCommand();
    if(cmd->flags == KCommandFlagReply){
      dataOut.Print(10);
      //Copy the data to non ptr array
      TTaskCtrlXMLPtrArray xml = dataOut.GetTaskCtrlXMLPtrArray();
      for(unsigned int i = 0; i< xml.size();i++){
        aTasksXML.push_back(xml[i]->GetText());
      }
      
      TTaskCtrlTaskStatePtrArray state = dataOut.GetTaskCtrlTaskStatePtrArray();
      for(unsigned int i = 0; i< state.size();i++){
        const TTaskCtrlTaskState *s = state[i];
        aStateArray.push_back(*s);
        
      }



      return true;
    }else{
      dPrint(1,"Error when getting task table");
      return false;
    }

    
  }else{
    dPrint(1,"no responce for get task state");
    return false;
  }

} 
//*****************************************************************************

bool CTaskCtrlClient::StartTaskCtrl()
{
 
  CTaskCtrlData dd;
  dd.CreateInternalBinBag();
  bool r = dd.SetCommand(TCommand(KCommandStartTaskCtrl,
                                  KCommandFlagDefault,
                                  TTaskCtrlTaskID(),
                                  0));
  assert(r == true);

  dd.Print(10);
  unsigned int i= 0;
  return SimpleDataSend(dd,i);

}
//*****************************************************************************

bool CTaskCtrlClient::StopTaskCtrl()
{

  CTaskCtrlData dd;
  dd.CreateInternalBinBag();
  bool r = dd.SetCommand(TCommand(KCommandStopTaskCtrl,
                                  KCommandFlagDefault,
                                  TTaskCtrlTaskID(),
                                  0));
  assert(r == true);

  dd.Print(10);
  unsigned int i= 0;
  return SimpleDataSend(dd,i);
}
//*****************************************************************************

bool CTaskCtrlClient::PauseTaskCtrl()

{

  
  CTaskCtrlData dd;
  dd.CreateInternalBinBag();
  bool r = dd.SetCommand(TCommand(KCommandPauseTaskCtrl,
                                  KCommandFlagDefault,
                                  TTaskCtrlTaskID(),
                                  0));
  assert(r == true);

  dd.Print(10);
  unsigned int i= 0;
  return SimpleDataSend(dd,i);
}
//*****************************************************************************
bool CTaskCtrlClient::GetCommandReply(CTaskCtrlData &aData, const int aMessageID, 
                                      const int aTimeout_ms)
{ 
  EMaCIError result;
  SMessageSource ms; // Compulsory for call to
                     // Receivesynchronousmessagereply, not used here
                     // though.

  // Call the ReceiveMessage wrapper with 2s timeout
  result = ReceiveSynchronousMessageReply(aData, ms, aMessageID, aTimeout_ms);
  
  // If result is OK, process the msg.
  if (result == KMaCIOK) {
    if (aData.GetCommand() == NULL) {
       dPrint(ODVINFO, "No command in reply");
       return false;
    }
    // Got message OK.  Basicly we don't need to do anything here, but
    // some interface may want to do some checks: for example, the
    // received message contains some specific element or information
    // before it is accepted.
  }
  else {
      
      if (result == KMaCITimeout) {
          dPrint(ODVINFO, "KMaCITimeout in ReceiveSynchronousMessageReply");
      }
      if (result == KMaCIError) {
          dPrint(ODVINFO, "KMaCIError in ReceiveSynchronousMessageReply");
      }
  }
  
  return (result == KMaCIOK);
}

//*****************************************************************************
/*
bool CTaskCtrlClient::GetCommandReply(CTaskCtrlData &aData, const int aMessageID, 
                                   const int aTimeout_ms)
{ 
  EMaCIError result;
  gimi::GIMIMessage gmsg;
  
  // Call the ReceiveMessage wrapper with 2s timeout
  result = ReceiveSynchronousMessageReply(gmsg, aMessageID, aTimeout_ms);
  
  // If result is OK, process the msg.
  if (result == KMaCIOK) {
    bool r;
    gim::binbag::CBinBag bb;
    CTaskCtrlData d;

    dPrint(2, "GIMI Got synch message");

    // Decode BinBag.
    r = bb.Decode(gmsg.getData(), gmsg.getDatalength());
    if (r) {
      // BinBag OK. Decode AuctionData.
      r = d.DecodeFrom(&bb);
      if (r) {
        // AuctionData ok. Copy to caller.
        aData.Copy(d);

      } else {
        result = KMaCIInvalidFormat;

      }

    } else {
      result = KMaCIInvalidFormat;
      
    }
  }
  return (result == KMaCIOK);
}
*/
//*****************************************************************************

bool CTaskCtrlClient::SendCommand(const CTaskCtrlData &aTaskCtrlData, const unsigned int aMessageID)
{
  EMaCIError result = KMaCIError;
  
  if (IsActive()) {
    if (aTaskCtrlData.GetCommand()) {
      // Send.
      SendInterfaceMessage(aTaskCtrlData.GetBinBagContainerPtr()->GetBuffer(),
                           aTaskCtrlData.GetBinBagContainerPtr()->GetBufferSize(),
                           aMessageID);
      
      dPrint(10,"SendInterfaceMessage called: %d:%d (%d bytes of payload sent)",
             iInterfaceMajor, iInterfaceMinor, 
             aTaskCtrlData.GetBinBagContainerPtr()->GetBufferSize());
      // Result
      result = KMaCIOK;
      
    } else {
      dPrint(2,"No 'TCommand' element in provided CTaskCtrlData object. Will not send!");
      result = KMaCIInvalidFormat;

    }
   
  } else {
    dPrint(2,"Unable to send TaskCtrlData - Interface is not active! (Open() not called?)");
    result = KMaCINotActive;

  }


  return (result == KMaCIOK);
}
//*****************************************************************************

bool CTaskCtrlClient::WaitForTaskCtrlEvent(CTaskCtrlData &aData,unsigned int *aSequence, unsigned int aTimeout_ms)
{
  bool result = false;

  Lock();
  aData.Reset();
  if (aSequence == NULL) {
    if(iTaskCtrlDataSequence > 0){
      aData = iLastTaskCtrlData;
      result = true;
    }
  }else{
    if(iTaskCtrlDataSequence <= *aSequence){
      int time_left = aTimeout_ms;
      unsigned int time_begin = ownTime_get_ms();
      Wait(time_left);
      time_left = aTimeout_ms - ownTime_get_ms_since(time_begin);
      if(time_left > 0){
        aData = iLastTaskCtrlData;
        *aSequence = iTaskCtrlDataSequence;
        result = true;
      }else{
        dPrint(4,"Failed to get lates task ctrl event");
      }
    }else{
      if(iTaskCtrlDataSequence > 0){
        aData = iLastTaskCtrlData;
        *aSequence = iTaskCtrlDataSequence;
        result = true;
      }
    }
  }
  Unlock();
  return result;


}
//*****************************************************************************

bool CTaskCtrlClient::GetDataBySynchronousCall(const CTaskCtrlData dataIn, CTaskCtrlData &dataOut, const unsigned int sequence,
                                                    const unsigned int aTimeout_ms)
{
  bool result = false;
  //CAuctionData rd;
  //CAuctionData dd;
  //dd.CreateInternalBinBag();

  // Only this func uses the sequence, so locking not required; BUT remember
  // correct locking scheme when this is not the case.
  //const unsigned int seq = ++iTaskCtrlCommandSequence;

  SendCommand(dataIn, sequence); //needs public wrap, increment iTaskCtrlCommandSequence

  // Now, get reply! (Give it 1000ms time to answer)
  GetCommandReply(dataOut, sequence, aTimeout_ms); //might need public wrap

  // Extract data.
  //const TCommand *de = dataOut.GetCommand();
  if (dataOut.GetCommand()==NULL) {
    dPrint(ODVINFO,"No command in container!");
  }
  else {
    result = true;
  }

  return result;
}

//*****************************************************************************
bool CTaskCtrlClient::SimpleDataSend(const CTaskCtrlData dataIn, unsigned int &sequence) {
    
    bool result = false;
    
    //const unsigned int seq = ++iTaskCtrlCommandSequence;
    
    result = SendCommand(dataIn, sequence); //needs public wrap, increment iTaskCtrlCommandSequence
    //sequence = seq;
    
    return result;
}
//*****************************************************************************
void *CTaskCtrlClient::GetTaskCtrlClientCallBackUserPtr(void) {
    return iCallBackUserPtr;
}


//*****************************************************************************
CTaskCtrlClientCallback *CTaskCtrlClient::GetTaskCtrlClientCallBack(void) {
    return iTaskCtrlClientCallback;
}

//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

int CTaskCtrlClient::ProcessMessage(const gimi::GIMIMessage &msg)
{
  int result = 0;
  gim::binbag::CBinBag bb;
  CTaskCtrlData tcd;
  bool r;

  r = bb.Decode(msg.getData(), msg.getDatalength());
  if (r) {
    // Succesfully decoded as BinBag.
    r = tcd.DecodeFrom(&bb);
    if (r) {
    





      const TCommand *cmd = tcd.GetCommand();
      if (cmd != NULL) {
        //// Some checks.
        
        // Call the handler(s) if set.
        if (iTaskCtrlClientCallback) {
          dPrint(2,"Got Callback for TaskCtrlDataEvent - executing!");
          iTaskCtrlClientCallback->OnTaskCtrlDataEvent(tcd,
                                                       iTaskCtrlDataSequence,
                                                       *this,
                                                       iCallBackUserPtr);
          dPrint(8,"Callback for TaskCtrlDataEvent - execution complete!");
        } 
      }
        
      
      else  {
        const TTaskCtrlStatusEvent *event = tcd.GetTaskCtrlStatusEvent();
        if (event != NULL) {
          //// Some checks.
          Lock();
          iTaskCtrlDataSequence++;      
          iLastTaskCtrlData = tcd;
          Notify();
          Unlock();
          // Call the handler(s) if set.
          if (iTaskCtrlClientCallback) {
            dPrint(2,"Got Callback for TaskCtrlDataEvent - executing!");
            iTaskCtrlClientCallback->OnTaskCtrlDataEvent(tcd,
                                                         iTaskCtrlDataSequence,
                                                         *this,
                                                         iCallBackUserPtr);
            dPrint(8,"Callback for TaskCtrlDataEvent - execution complete!");
          } 
        }
      }
      
    } else {
      dPrint(4,"WARNING: Received TaskCtrl interface message, but failed to decode as TaskCtrlData!");
      
    }
  }
  
  return result;
}

//*****************************************************************************

int CTaskCtrlClient::ThreadFunction(const int aThreadNumber)
{
  int result = 0;
  const unsigned int hard_error_count_limit = 10;
  unsigned int hard_error_count = 0;
  EMaCIError e;
  gimi::GIMIMessage gmsg;
  
  assert(aThreadNumber == 0);
  assert(iGIMIPtr != NULL);
  
  dPrint(8, "GIMIMessage handler started");
  
  // Run as long as the thread should be active
  while(IsActive()) {
    // Call the ReceiveMessage wrapper with 1s timeout
    e = ReceiveInterfaceMessage(gmsg, 1000);
    if (e == KMaCIOK) {
      ProcessMessage(gmsg);

      // Reset error counter.
      if (hard_error_count) hard_error_count = 0;

    } else if (e != KMaCITimeout) {
      // Increment hard error count
      ++hard_error_count;
      
      // Check whether the hard error count limit is still under limit. 
      if (hard_error_count < hard_error_count_limit) {
        // Other error, try to recover by sleeping one second.
        dPrint(10,"ProcessMessage returned error %u, trying to recover by sleeping 1000ms (%u attempts left)",
               e, hard_error_count_limit-hard_error_count);
        ownSleep_ms(1000);

      } else {
        dPrint(3,"Error Recovery failed, TaskCtrlClient ThreadFunction terminating...");

        // Break the while().
        break;
      }
      
    }
  }
  
  dPrint(8, "GIMIMessage handler stopped");
  SetActive(false);

  return result;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
